//
//  ALPTopHotViewController.m
//  AlpFM
//
//  Created by KING on 16/3/1.
//  Copyright © 2016年 Alp. All rights reserved.
//

#import "ALPTopHotViewController.h"
#import "MJRefresh.h"
#import "ALPListerModel.h"
#import "ALPTopHotTableViewCell.h"
#import <AFNetworking.h>
#import "ALPPlayViewController.h"
@interface ALPTopHotViewController ()
<UITableViewDataSource,
UITableViewDelegate
//,HFLisionDetialCellDelegate
>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, assign) BOOL isUpLoading;
@property (nonatomic,assign) NSInteger nextPage; //记录下一页
@property (nonatomic, strong) NSString *maxPageID;//最大页码
@end

@implementation ALPTopHotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //铺tableView
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT- 100) style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.myTableView registerClass:[ALPTopHotTableViewCell class] forCellReuseIdentifier:@"group"];
    
    self.allArray = [NSMutableArray array];
    //下拉刷新
    self.isUpLoading = NO;
    [self p_addHeader];
    [self p_addFooter];
}
#pragma mark - 下拉刷新
- (void)p_addHeader{
    
    [self.myTableView addHeaderWithCallback:^{
        self.nextPage = 1;
        self.isUpLoading = NO;
        //重新请求数据
        [self p_getDataWithPage:self.nextPage];
    }];
    [self.myTableView headerBeginRefreshing];
}

#pragma mark - 上拉刷新
- (void)p_addFooter{
    
    [self.myTableView addFooterWithCallback:^{
        self.nextPage++;
        self.isUpLoading = YES;
        [self p_getDataWithPage:self.nextPage];
        
    }];
}

#pragma mark - 协议方法 行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}

#pragma mark - 协议方法 cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ALPTopHotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"group"];
    cell.model = [self.allArray objectAtIndex:indexPath.row];
    //    cell.textLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
//    cell.MyDelegate = self;
    return cell;
}

#pragma mark - 协议方法 高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0.267*SCREEN_WIDTH;
}


#pragma mark - 获取数据
- (void)p_getDataWithPage:(NSInteger)page{
    //接收数据需要页码,标题和pageID(点击ID)
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/rankingList/track?device=android&key=%@&pageId=%ld&pageSize=40", self.key, (long)page];
    
    //    NSLog(@"%@", url);
    //中文解码
    NSString *urlEncode = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    
    [session GET:urlEncode parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
//                NSLog(@"成功");
#pragma mark -- 下拉清除
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.allArray removeAllObjects];
        }
        
#pragma mark -- 获取最大页码
        self.maxPageID = [responseObject objectForKey:@"maxPageId"];
        //                        NSLog(@"页码最大数%@", self.maxPageID);
        
#pragma mark -- 加载数据
        if (page <= self.maxPageID.intValue) {
            NSMutableArray *array = [responseObject objectForKey:@"list"];
            for (NSMutableDictionary *dic in array) {
                ALPListerModel *model = [[ALPListerModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
//                ALPListerModel *model = [[ALPListerModel alloc] initWithDictionary:dic];
                [self.allArray addObject:model];
            }
        }
        
#pragma mark --  停止菊花
        [self.myTableView reloadData];
        [self.myTableView headerEndRefreshing];
        [self.myTableView footerEndRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"失败");
        
    }];
    
}

#pragma mark -- 点击分类的详情页(列表)会直接播放歌曲
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    ALPPlayViewController *player = [ALPPlayViewController sharePlayerViewController];
    
    ALPListerModel *model = [self.allArray objectAtIndex:indexPath.row];
    player.song_ID = model.trackID.intValue;      //歌曲的ID
    player.indexRow = indexPath.row;     //点击的歌曲的下标
    
    //***************** 数组转换 ****************
    NSMutableArray *array = [NSMutableArray array];
    for (ALPListerModel *lisionModel in self.allArray) {
        ALPSingleModel *listModel = [[ALPSingleModel alloc] init];
        //        NSLog(@"AAA%@", lisionModel.trackID);
        listModel.trackId = [NSString stringWithFormat:@"%@", lisionModel.trackID];
        listModel.title = lisionModel.title;
        listModel.playtimes = lisionModel.playsCounts;
        listModel.comments = lisionModel.commentsCounts;
        listModel.duration = lisionModel.duration;
        [array addObject:listModel];
    }
    player.allMusicArray = array;//歌曲数组赋值
    // ******************************************
    
    [self presentViewController:player animated:YES completion:^{
    }];
    
    
}

#pragma mark -- 轻扫手势代理
- (void)popLastPage{
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5f;
    animation.type = @"push";
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
